package com.wzy.Controller;


import com.wzy.entity.Blog;
import com.wzy.service.ArchivesService;
import com.wzy.service.BlogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author why
 * @since 2021-02-19
 */
@Api("时间轴")
@Controller
public class ArchivesController {


    @Autowired
    private BlogService blogsService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 跳转到时间轴页面,默认显示1931年,按年份查询blog表，查询出1-12月
     *
     * @return
     */
    @ApiOperation("时间轴操作")
    @GetMapping("/archives/{year}")
    public String routerbattlePage(@PathVariable(value = "year", required = false) String year,
                                   Model model) {

        if (year == null) {
            year = "1931";
        }
        List<Blog> months = null;
        //先去缓存中查12个月
        months = redisTemplate.opsForList().range(year, (long) 0, (long) -1);
        if (months.size()==0) {
            //缓存中无12个月，去数据库中查
            months = blogsService.getMonthListByYear(year);
            for (Blog month : months) {
                redisTemplate.opsForList().rightPush(year, month);
            }
             //保存5分钟
             redisTemplate.expire(year,10, TimeUnit.MINUTES);
        }
        model.addAttribute("months", months);
        model.addAttribute("curYear", year);
        return "archives";
    }


}

